import { unauthorized } from '@/api/login'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({  
    history: createWebHistory(),
    routes: [  
        {  
            path: '/',
            redirect: '/login',
            name: 'welcome',
            component: () => import('@/views/WelcomeView'), // 直接导入
            children: [  
                {
                    path: '/login',
                    name: 'login',
                    component: () => import('@/views/login/loginPage.vue') // 直接导入
                }, {
                    path: 'reset',
                    name: 'reset',
                    component: ()=> import('@/views/reset/ResetPage.vue')
                }
            ]  
        }, {
            // 这个是主页
            path: '/index',
            name: 'index',
            component: () => import('@/views/indexView.vue')
        },
        {
            path: '/:pathMatch(.*)*',
            component: () => import('@/views/other/notFound.vue')
        }
    ]  
})

// 路由守卫
router.beforeEach((to, from, next) => {

    // 是否登录
    const isUnauthorized = unauthorized()

    // 已登录 - 允许进入首页
    if (to.name && to.name.startsWith('welcome-') && !isUnauthorized) {
        next('/index');
    }
    // 未登录 - 重定向到登录页面
    else if (to.path === '/index' && isUnauthorized) {
        next('/')
    }
    // 其他，正常跳转
    else {
        next();
    }
})

export default router